package com.xxl.job.executor.service.jobhandler;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpUtil;
import com.godtree.enums.WranEnum;
import com.godtree.exception.HealthCheckException;
import com.godtree.util.WranMsgUtils;
import com.google.common.collect.Lists;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.stereotype.Component;

import java.net.URL;
import java.util.concurrent.TimeUnit;

/**
 * @author lisicheng
 * @date 20220719
 */
@Component
public class HealthCheckJob {


  @XxlJob("healthCheckJob")
  public void healthCheck() {
    String jobParam = XxlJobHelper.getJobParam();
    String text = StrUtil.format("请配置健康检查url参数：{}", jobParam);
    if (StrUtil.isBlank(jobParam)) {
      WranMsgUtils.send(WranEnum.HEALTH_CHECK.getTitle(), text);
      XxlJobHelper.handleFail(text);
      return;
    }
    URL url = URLUtil.url(jobParam);
    if (url == null) {
      WranMsgUtils.send(WranEnum.HEALTH_CHECK.getTitle(), text);
      XxlJobHelper.handleFail(text);
      return;
    }
    // 如果url不是以http https开头的
    String http = "http";
    String https = "https";
    if (!Lists.newArrayList(http, https).contains(url.getProtocol())) {
      WranMsgUtils.send(WranEnum.HEALTH_CHECK.getTitle(), text);
      XxlJobHelper.handleFail(text);
      return;
    }
    String healthCheck = "healthCheck";
    if (!jobParam.contains(healthCheck)) {
      WranMsgUtils.send(WranEnum.HEALTH_CHECK.getTitle(), text);
      XxlJobHelper.handleFail(text);
      return;
    }
    try {
      String result = HttpUtil.get(jobParam, (int) TimeUnit.SECONDS.toMillis(3));
      String success = "success";
      if (success.equals(result)) {
        return;
      }
      String content = "result is not success";
      WranMsgUtils.send(WranEnum.HEALTH_CHECK.getTitle(), content);
      throw new HealthCheckException(content);
    } catch (Exception e) {
      String content = StrUtil.format("健康检查失败，请检查服务是否正常运行：{}；异常：{}", jobParam,
          ExceptionUtil.stacktraceToString(e));
      WranMsgUtils.send(WranEnum.HEALTH_CHECK.getTitle(), text);
      XxlJobHelper.handleFail(content);
    }

  }

}
